package util;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This is the visible class (Facade) of this package. It represents a connector
 * that listen for xml documents on a specific port and may send xml documents
 * to a specific port on a remote machine.
 * 
 * This class is abstract. You should create a new class that inherits this
 * class and implement "receive(String)" and "reportException(Exception)"
 * methods.
 * 
 * @author Leonardo Murta e Vanessa Braganholo
 */
public abstract class Connector
{

	/**
	 * Constructs the connector.
	 * 
	 * @param port
	 *            Port listened by the connector.
	 */
	public Connector(int port) throws IOException
	{
		Thread thread = new Thread(new Server(this, port));
		thread.start();
	}

	/**
	 * Send a xml document.
	 * 
	 * @param host
	 *            Target host.
	 * @param port
	 *            Target port on host.
	 * @param xml
	 *            XML document to be sent.
	 */
	public void send(String host, int port, String xml) throws UnknownHostException, IOException
	{
		Socket socket = new Socket(host, port);
		PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
		printWriter.print(xml);
		printWriter.close();
		socket.close();
	}

	/**
	 * This method should be implemented by classes that want to receive xml
	 * documents. This method is called for each received xml document.
	 * 
	 * @param xml
	 *            XML document received.
	 */
	public abstract void receive(String xml);

	/**
	 * This method informs the exception thrown during sending or receiving xml
	 * documents. A simple implementation of this method may call
	 * "e.printStackTrace()".
	 * 
	 * @param exception
	 *            The exception thrown during sending or receiving xml
	 *            documents.
	 */
	public abstract void reportException(Exception exception);
}
